package com.yk.i_wms.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yk.i_wms.common.model.PageResult;
import com.yk.i_wms.common.model.Result;
import com.yk.i_wms.dto.PdtBomDTO;
import com.yk.i_wms.model.PdtBom;
import com.yk.i_wms.service.IPdtBomService;
import com.yk.i_wms.util.EasyPoiExcelUtil;
import com.yk.i_wms.vo.BomTreeVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * BOM
 * @author hbq
 * @date 2021-03-29 16:32:54
 */
@Slf4j
@CrossOrigin
@RestController
@Api(tags = "BOM")
@RequestMapping("pdt")
public class PdtBomController {
    @Autowired
    private IPdtBomService pdtBomService;

    /**
     * 根据机种号查询所有最小子级列表
     */
    @ApiOperation(value = "根据机种号查询所有最小子级列表")
    @PostMapping("/pdtBom/getMinSonListByModelCode")
    public Result getMinSonListByModelCode(@RequestBody Map<String, Object> params) {
        String modelCode = MapUtil.getStr(params, "modelCode");
        return Result.succeed(pdtBomService.getMinSonList(modelCode), "查询成功");
    }

    /**
     * 根据机种号查询所有树形子级
     * @param params
     */
    @ApiOperation(value = "根据机种号查询所有树形子级")
    @PostMapping("/pdtBom/getTreeListByModelCode")
    public Result getTreeListByModelCode(@RequestBody Map<String, Object> params) {
        String modelCode = MapUtil.getStr(params, "modelCode");
        List<BomTreeVO> bomTreeVO= pdtBomService.getTreeListByModelCode(modelCode);
        return Result.succeed(bomTreeVO, "查询成功");
    }

    /**
     * 根据机种号查询最高根级列表
     */
    @ApiOperation(value = "根据机种号查询最高根级列表")
    @PostMapping("/pdtBom/getRootListByModelCode")
    public Result getRootListByModelCode(@RequestBody Map<String, Object> params) {
        String itemCode = MapUtil.getStr(params, "itemCode");
        List<PdtBom> boms= pdtBomService.getRootListByModelCode(itemCode);
        return Result.succeed(boms, "查询成功");
    }
    /**
     * 列表
     */
    @ApiOperation(value = "查询列表")
    @PostMapping("/pdtBom/list")
    public Result<PageResult> list(@RequestBody Map<String, Object> params) {
        Page<Map> list= pdtBomService.findList(params);
        return Result.succeed(PageResult.restPage(list),"查询成功");
    }

    /**
     * 查询
     */
    @ApiOperation(value = "查询")
    @PostMapping("/pdtBom/sel/{id}")
    public Result findUserById(@PathVariable Long id) {
        PdtBom model = pdtBomService.getById(id);
        return Result.succeed(model, "查询成功");
    }

    /**
     * 新增or更新
     */
    @ApiOperation(value = "新增or更新")
    @PostMapping("/pdtBom/save")
    public Result save(@RequestBody PdtBom pdtBom) {
        pdtBomService.saveOrUpdate(pdtBom);
        return Result.succeed("保存成功");
    }

    /**
         * 批量新增or更新
         */
    @ApiOperation(value = "批量新增or更新")
    @PostMapping("/pdtBom/saveBatch")
    public Result saveBatch(@RequestBody Map<String,List<PdtBom>> map) {
        List<PdtBom> models = map.get("models");
        pdtBomService.saveOrUpdateBatch(models);
        return Result.succeed("保存成功");
    }

    /**
     * 删除
     */
    @ApiOperation(value = "批量删除")
    @PostMapping("/pdtBom/del")
    public Result delete(@RequestBody Map<String,List<Long>> map) {
        List<Long> ids = map.get("ids");
        pdtBomService.removeByIds(ids);
        return Result.succeed("删除成功");
    }
    
    /**
     * 导入
     */
    @ApiOperation(value = "导入")
    @PostMapping("/pdtBom/leadIn")
    public  Result leadIn(MultipartFile excel) throws Exception {
        if (!excel.isEmpty()) {
            List<PdtBomDTO> list = EasyPoiExcelUtil.importExcel(excel, 1, 1, PdtBomDTO.class);
            //过滤无料号数据
            list=list.stream().filter(u-> StrUtil.isNotBlank(u.getItemCode())).collect(Collectors.toList());
            for (int i = 0; i <list.size(); i++) {
                PdtBomDTO bomDTO = list.get(i);
                int level = bomDTO.getLevel();
                //一级物料直接存
                if(bomDTO.getLevel()==1){
                    bomDTO.setParentId(0L);
                }else{
                    //非1级物料寻找最近上级
                    for (int j=i;;j--){
                        PdtBomDTO endBom = list.get(j);
                        if(endBom.getLevel()==level-1){
                            bomDTO.setParentId(endBom.getId());
                            break;
                        }
                    }
                }
                pdtBomService.save(bomDTO);
            }
        }
        return Result.succeed("导入成功");
    }
    
    /**
     * 导出（传入ids数组，选择指定id）
     */
    @ApiOperation(value = "导出（传入ids数组，选择指定id）")
    @PostMapping("/pdtBom/leadOut")
    public void leadOut(@RequestBody Map<String,List<Long>> map,HttpServletResponse response) throws IOException {
        List<Long> ids = map.get("ids");
        List<PdtBom> pdtBomList = ids==null||ids.isEmpty()? pdtBomService.list(new QueryWrapper<>()):(List)pdtBomService.listByIds(ids);
        //导出操作
        EasyPoiExcelUtil.exportExcel(pdtBomList, "BOM 导出（导入时将“父级id”换成“层”）", "BOM 导出（导入时将“父级id”换成“层”）", PdtBom.class, "pdtBom.xls", response);
    }
    @ApiOperation(value = "导入")
    @PostMapping("/pdtBom/leadInTest")
    public  Result leadInTest(MultipartFile excel) throws Exception {
        ExcelReader reader = ExcelUtil.getReader(excel.getInputStream());
        List<List<Object>> read = reader.read(0, 4);

        System.out.println(read.get(0).get(1));
        for (List<Object> objects : read) {
            System.out.println(objects);
        }
        return Result.succeed("导入成功");
    }

}
